<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\CollectionGoods;
use Endroid\QrCode\QrCode;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\GoodsSpecificationKey;
use app\admin\model\GoodsSpecificationVal;
use app\admin\model\GoodsSpecificationSku;
use think\Session;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend {

    /**
     * Goods模型对象
     * @var \app\admin\model\Goods
     */
    protected $model = null;
    // 需要填写你的 Access Key 和 Secret Key
    protected $accessKey = "CUtx52ljBon1apOo8w9ei-F32lS1pywghBU8tNkt";
    protected $secretKey = "ZHqatwaCHkQfygoKVKESyff3YV1F0fwUqeoYartZ";
    protected $bucket = "shanzuo";

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\Goods;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("recommendList", $this->model->getRecommendList());
        $this->view->assign("isShipList", [0 => '商家包邮', 1 => '运费模板']);
        $this->view->assign("freightTypeList", [0 => '计件', 1 => '计重']);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index() {

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //            $admin_id=$admin = Session::get('admin');
            //            $where1 = array();
            //            if ($admin_id['id'] !== 1){
            //                $where1['merchant_id'] = ['eq',$admin_id['id']];
            //            }
            $total = $this->model->with(['category3', 'category2', 'category1'])->where($where)
                //  ->where($where1)
                ->order($sort, $order)->count();

            $list = $this->model->with(['category3', 'category2', 'category1'])->where($where)
                //   ->where($where1)
                ->order($sort, $order)->limit($offset, $limit)->select();


            foreach ($list as $row) {
                $row->visible(['id', 'category_id', 'qrwechatcode', 'brand_id', 'name', 'goods_price', 'sold_number', 'qrcode', 'thumbnail_image', 'goods_images', 'content', 'status', 'recommend', 'createtime', 'updatetime']);
                $row->visible(['category1']);
                $row->getRelation('category1')->visible(['name']);
                $row->visible(['category2']);
                $row->getRelation('category2')->visible(['name']);
                $row->visible(['category3']);
                $row->getRelation('category3')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add() {
        $time = time();
        if ($this->request->isPost()) {
            $params = $this->request->post();

            if ($params) {

                //                $CustomsClearance = \app\admin\model\CustomsClearance::where('declareNo',$goods['declareNo'])->find();
                //                dump($CustomsClearance);
                //                dd($goods);
                if (!isset($params['attrs']['group']))
                    $this->error('请填写规格');
                if (empty($params['attrs']['items'][0]))
                    $this->error('请填写规格参数');
                foreach ($params['attrs']['market_price'] as $v) {
                    if (empty($v)) {
                        $this->error('请填写原价');
                    }
                }
                foreach ($params['attrs']['price'] as $v) {
                    if (empty($v)) {
                        $this->error('请填写现价');
                    }
                }
                foreach ($params['attrs']['stock'] as $v) {
                    if (empty($v)) {
                        $this->error('请填写库存');
                    }
                }
                foreach ($params['attrs']['image'] as $v) {
                    if (empty($v)) {
                        $this->error('请选择图片');
                    }
                }
                $sh = $admin = Session::get('admin');
                //求商品的最大值
                $max2 = max($params['attrs']['price']);
                $max1 = max($params['attrs']['market_price']);
                $max = $max1 < $max2 ? $max2 : $max1;
                $min1 = min($params['attrs']['price']);
                $min2 = min($params['attrs']['market_price']);
                $min = $min1 < $min2 ? $min1 : $min2;
                Db::startTrans();
                try {
                    //插入商品 获取商品id
                    $goods_data = $params['row'];
                    // $goods_data['merchant_id'] = $sh['id'];
                    $goods_data['createtime'] = $time;
                    $goods_data['updatetime'] = $time;
                    $goods_data['goods_price'] = $min;
                    $goods_data['goods_price_max'] = $max;
                    $goods_id = db('goods')->insertGetId($goods_data);
                    if ($goods_id) {
                        foreach ($params['attrs']['group'] as $k => $v) {
                            $key_params = ['name' => $v, 'goods_id' => $goods_id, 'createtime' => $time, 'updatetime' => $time,];
                            //规格键
                            $key_id = db('goods_specification_key')->insertGetId($key_params);
                            $val_data = explode(',', $params['attrs']['items'][$k]);
                            foreach ($val_data as $kk => $vv) {
                                $val_params = array();
                                $val_params[$kk]['goods_specification_key_id'] = $key_id;
                                $val_params[$kk]['value'] = $vv;
                                $val_params[$kk]['createtime'] = $time;
                                $val_params[$kk]['updatetime'] = $time;
                                //规格值
                                db('goods_specification_val')->insertAll($val_params);
                            }
                        }
                        $sku_params = array();
                        //获取本次插入的key
                        $key_data = db('goods_specification_key')->where('goods_id', $goods_id)->select();

                        //获取每个key下面val
                        $value_data = array();
                        foreach ($key_data as $k => $v) {
                            $value_data[$k] = db('goods_specification_val')->where('goods_specification_key_id', $v['id'])->select();
                        }

                        //in
                        $val_id = array();
                        foreach ($value_data as $k => $v) {
                            foreach ($v as $kk => $vv) {
                                $val_id[$k][$kk] = $vv['id'];
                            }
                        }

                        //去重,重新排列键
                        $sku1 = array_flip($params['attrs']['sku1']);
                        $sku1 = array_keys($sku1);

                        $specification = array();
                        foreach ($sku1 as $kkk => $vvv) {
                            $specification[$kkk] = explode(',', $vvv);
                        }

                        $attr_symbol_path = array();
                        foreach ($specification as $k => $v) {
                            $in = '';
                            foreach ($v as $k2 => $v2) {
                                $name = db('goods_specification_val')->where('id', 'in', $val_id[$k2])->where('value', 'eq', $v2)->find();
                                $in .= $name['id'] . '-';
                                $attr_symbol_path[$k] = $in;
                            }
                        }
                        //标识
                        foreach ($attr_symbol_path as $k => $v) {
                            $info = rtrim($v, '-');
                            $sku_params[$k]['attr_symbol_path'] = $info;
                            $sku_params[$k]['goods_id'] = $goods_id;
                            $sku_params[$k]['createtime'] = $time;
                            $sku_params[$k]['updatetime'] = $time;
                            $skuValIds = str_replace('-', ',', $info);
                            $skuValInfo = db('goods_specification_val')->whereIn('id', $skuValIds)->column('value');
                            $skuValName = implode(',', $skuValInfo);
                            $sku_params[$k]['name'] = $skuValName;
                        }
                        //原价
                        foreach ($params['attrs']['market_price'] as $k => $v) {
                            $sku_params[$k]['original_price'] = $v;
                        }
                        //现价
                        foreach ($params['attrs']['price'] as $k => $v) {
                            $sku_params[$k]['current_price'] = $v;
                        }
                        //库存
                        foreach ($params['attrs']['stock'] as $k => $v) {
                            $sku_params[$k]['stock'] = $v;
                        }
                        //图片
                        foreach ($params['attrs']['image'] as $k => $v) {
                            $sku_params[$k]['images'] = $v;
                        }
                        db('goods_specification_sku')->insertAll($sku_params);

                        //如果商品保存成功了 生成二维码
                        // $content 一般为url地址 当然也可以是文字内容
                        $content = 'http://wxshop.191292.net/pages/goods/goodsDetails?id=' . $goods_id;
                        $qrCode = new QrCode($content);
                        // 指定内容类型
                        header('Content-Type: ' . $qrCode->getContentType());
                        // 输出二维码
                        //   echo $qrCode->writeString();
                        $fontPath = ROOT_PATH . 'public/uploads/qrcode/' . time() . rand(1000, 9999) . 'qrcode.png';
                        //                    dump($qrCode->writeString());
                        //                    die();
                        $qrCode->writeFile($fontPath);

                        $auth = new Auth($this->accessKey, $this->secretKey);
                        // 生成上传 Token
                        $token = $auth->uploadToken($this->bucket);
                        // 要上传文件的本地路径
                        // 上传到七牛后保存的文件名
                        $key = 'uploads/qrcode/' . time() . rand(1000, 9999) . 'qrcode.png';
                        $uploadMgr = new UploadManager();
                        // 调用 UploadManager 的 putFile 方法进行文件的上传。

                        list($ret, $err) = $uploadMgr->putFile($token, $key, $fontPath);
                        if ($err !== null) {
                            $this->error('上传失败');
                        }
                        $wechatimg = getwxacode($goods_id);
                        $token1 = $auth->uploadToken($this->bucket);
                        // 要上传文件的本地路径
                        // 上传到七牛后保存的文件名
                        $key1 = 'uploads/qrwechatcode/' . time() . rand(1000, 9999) . 'qrwechatcode.png';
                        $uploadMgr = new UploadManager();
                        // 调用 UploadManager 的 putFile 方法进行文件的上传。

                        list($ret, $err) = $uploadMgr->putFile($token1, $key1, $wechatimg);
                        if ($err !== null) {
                            $this->error('上传失败');
                        }
                        $this->model->where('id', '=', $goods_id)->update(['qrwechatcode' => $key1, 'qrcode' => $key]);
                    }
                    $result = true;


                    $goods = $params['goods'];

                    $goods['customs_id'] = $goods['declareNo'];

                    unset($goods['declareNo']);


                    $goods['is_succ'] = 2;
                    \app\admin\model\CustomsGoods::create($goods);

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $result = $e->getMessage();
                }
                if ($result === true) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null) {
        $time = time();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $key_model = new GoodsSpecificationKey();
        $val_model = new GoodsSpecificationVal();
        //商品组合
        $sku_model = new GoodsSpecificationSku();
        $sku_list = toArray($sku_model->where('goods_id', 'eq', $ids)->select());
        $skus = array();
        foreach ($sku_list as $k => $v) {
            $skus[$k]['id'] = $v['id'];
            $skus[$k]['product_id'] = $v['goods_id'];
            $val_arr = explode('-', $v['attr_symbol_path']);
            $keys = '';
            $keys_id = '';
            $value = '';
            foreach ($val_arr as $kk => $vv) {
                $val_info = toArray($val_model->where('id', 'eq', $vv)->whereNull('deletetime')->find());
                $key_info = toArray($key_model->where('id', 'eq', $val_info['goods_specification_key_id'])->whereNull('deletetime')->find());
                $keys .= $key_info['name'] . ',';
                $keys_id .= $val_info['goods_specification_key_id'] . ',';
                $value .= $val_info['value'] . ',';
            }
            //keys
            $skus[$k]['keys'] = rtrim($keys, ',');
            $skus[$k]['keys_id'] = rtrim($keys_id, ',');
            $skus[$k]['value'] = rtrim($value, ',');
            $skus[$k]['value_id'] = implode(',', $val_arr);
            $skus[$k]['price'] = $v['current_price'];
            $skus[$k]['stock'] = $v['stock'];
            $skus[$k]['market_price'] = $v['original_price'];
            $skus[$k]['image'] = $v['images'];
        }
        $skus_json = json_encode($skus, true);

        //        echo $skus_json;die();
        //键值
        $attrItems = array();
        $key_list = $key_model->where('goods_id', 'eq', $ids)->select();
        foreach ($key_list as $k => $v) {
            $aa = $val_model->where('goods_specification_key_id', 'eq', $v['id'])->select();
            foreach ($aa as $kk => $vv) {
                $attrItems[$k][$kk] = $vv['value'];
            }
        }
        $attrItems_json = json_encode($attrItems);
        //编辑数据
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if (!isset($params['attrs']['group']))
                    $this->error('请填写规格');
                if (empty($params['attrs']['items'][0]))
                    $this->error('请填写规格参数');
                foreach ($params['attrs']['group'] as $v) {
                    if (empty($v)) {
                        $this->error('请填写规格');
                    }
                }
                foreach ($params['attrs']['items'] as $v) {
                    if (empty($v)) {
                        $this->error('请填写规格值');
                    }
                }
                foreach ($params['attrs']['market_price'] as $v) {
                    if (empty($v)) {
                        $this->error('请填写市场价');
                    }
                }
                foreach ($params['attrs']['price'] as $v) {
                    if (empty($v)) {
                        $this->error('请填写销售价');
                    }
                }
                foreach ($params['attrs']['stock'] as $v) {
                    if (empty($v)) {
                        $this->error('请填写库存');
                    }
                    if ($v <= 0) {
                        $this->error('库存不可为0');
                    }
                }
                foreach ($params['attrs']['image'] as $v) {
                    if (empty($v)) {
                        $this->error('请选择图片');
                    }
                }
                //求商品的最大值
                $max2 = max($params['attrs']['price']);
                $max1 = max($params['attrs']['market_price']);
                $max = $max1 < $max2 ? $max2 : $max1;
                $min1 = min($params['attrs']['price']);
                $min2 = min($params['attrs']['market_price']);
                $min = $min1 < $min2 ? $min1 : $min2;

                //软删之前的规格数据
                Db::startTrans();
                try {
                    //  db('goods_specification_sku')->where('goods_id',$ids)->update(['deletetime' => $time]);
                    $key_info = toArray($key_model->where('goods_id', $ids)->select());
                    if ($key_info) {
                        $key_in_id = array();
                        foreach ($key_info as $k => $v) {
                            $key_in_id[$k] = $v['id'];
                        }
                    }
                    //   db('goods_specification_key')->where('goods_id',$ids)->update(['deletetime' => $time]);
                    //    db('goods_specification_val')->where('goods_specification_key_id','in',$key_in_id)->update(['deletetime' => $time]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
                $key_name_list = $key_model->where('goods_id', 'eq', $ids)->column('name');


                //重新插入数据
                // 启动事务
                Db::startTrans();
                try {
                    db('goods_specification_key')->where('goods_id', $ids)->update(['deletetime' => $time]);
                    $goods_data = array();
                    $goods_data = $params['row'];
                    $goods_data['updatetime'] = $time;
                    $goods_data['goods_price'] = $min;
                    $goods_data['goods_price_max'] = $max;
                    //修改商品
                    db('goods')->where('id', $ids)->update($goods_data);
                    //规格键
                    foreach ($params['attrs']['group'] as $k => $v) {
                        $key_params = ['name' => $v, 'goods_id' => $ids, 'createtime' => $time, 'updatetime' => $time,];
                        //规格键
                        $is_has_spec_key = in_array($v, $key_name_list, true);
                        if ($is_has_spec_key) {
                            $key_name_Info = db('goods_specification_key')->where('goods_id', 'eq', $ids)->where('name', '=', $v)->find();
                            $key_id = $key_name_Info['id'];
                            $key_model->update(['deletetime' => NULL], ['id' => $key_id]);
                        } else {
                            $key_id = db('goods_specification_key')->insertGetId($key_params);
                        }

                        $val_data = explode(',', $params['attrs']['items'][$k]);
                        //获取当前规格key值
                        $value_name = db('goods_specification_val')->where('goods_specification_key_id', '=', $key_id)->column('value');
                        db('goods_specification_val')->where('goods_specification_key_id', '=', $key_id)->update(['deletetime' => $time]);
                        foreach ($val_data as $kk => $vv) {

                            $is_has_spec_val = in_array($vv, $value_name, true);

                            $val_params = array();
                            $val_params['goods_specification_key_id'] = $key_id;
                            $val_params['value'] = $vv;
                            $val_params['createtime'] = $time;
                            $val_params['updatetime'] = $time;

                            if ($is_has_spec_val) {
                                //$key_name_Info =  db('goods_specification_val')->where('goods_specification_key_id','eq',$key_id)->where('value','=',$vv)->find();
                                $val_model->update(['deletetime' => NULL], ['goods_specification_key_id' => $key_id, 'value' => $vv]);
                            } else {
                                db('goods_specification_val')->insert($val_params);
                            }

                            //规格值
                        }

                    }

                    $sku_params = array();
                    //获取本次插入的key
                    $key_data = toArray($key_model->where('goods_id', $ids)->select());

                    //获取每个key下面val
                    $value_data = array();
                    foreach ($key_data as $k => $v) {
                        $value_data[$k] = toArray($val_model->where('goods_specification_key_id', $v['id'])->select());
                    }
                    //in
                    $val_id = array();
                    foreach ($value_data as $k => $v) {
                        foreach ($v as $kk => $vv) {
                            $val_id[$k][$kk] = $vv['id'];
                        }
                    }

                    //组合
                    $specification = json_decode($params['attrs']['sku'], true);
                    $attr_symbol_path = array();
                    foreach ($specification as $k => $v) {
                        $in = '';
                        foreach ($v as $k2 => $v2) {
                            $name = toArray($val_model->where('id', 'in', $val_id[$k2])->where('value', 'eq', $v2)->find());
                            $in .= $name['id'] . '-';
                            $attr_symbol_path[$k] = $in;
                        }
                    }
                    //标识
                    foreach ($attr_symbol_path as $k => $v) {
                        $info = rtrim($v, '-');
                        $sku_params[$k]['attr_symbol_path'] = $info;
                        $sku_params[$k]['goods_id'] = $ids;
                        $sku_params[$k]['createtime'] = $time;
                        $sku_params[$k]['updatetime'] = $time;
                        $skuValIds = str_replace('-', ',', $info);
                        $skuValInfo = $val_model->whereIn('id', $skuValIds)->column('value');
                        $skuValName = implode(',', $skuValInfo);
                        $sku_params[$k]['name'] = $skuValName;
                    }
                    //原价
                    foreach ($params['attrs']['market_price'] as $k => $v) {
                        $sku_params[$k]['original_price'] = $v;
                    }
                    //现价
                    foreach ($params['attrs']['price'] as $k => $v) {
                        $sku_params[$k]['current_price'] = $v;
                    }
                    //库存
                    foreach ($params['attrs']['stock'] as $k => $v) {
                        $sku_params[$k]['stock'] = $v;
                    }
                    //图片
                    foreach ($params['attrs']['image'] as $k => $v) {
                        $sku_params[$k]['images'] = $v;
                    }
                    //id
                    $sku_model->where('goods_id', '=', $ids)->whereNull('deletetime')->update(['deletetime' => time()]);
                    //   dump($params['attrs']['id']);

                    if (isset($params['attrs']['id'])) {
                        foreach ($params['attrs']['id'] as $k => $v) {
                            if ($v) {
                                $sku_model->update(['deletetime' => NULL], ['id' => $v]);
                                $sku_model->where('id', '=', $v)->update($sku_params[$k], ['id' => $v]);
                                unset($sku_params[$k]);
                            }
                        }

                        array_values($sku_params);
                    }

                    if ($sku_params) {
                        db('goods_specification_sku')->insertAll($sku_params);
                    }
                    $result = true;
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $result = $e->getMessage();
                }
                if ($result === true) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("skus_json", $skus_json);
        $this->view->assign("attrItems_json", $attrItems_json);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "") {
        $time = time();
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $key_model = new GoodsSpecificationKey();
            //软删数据
            Db::startTrans();
            try {
                //商品
                db('goods')->where('id', 'in', $ids)->update(['deletetime' => $time]);
                //sku
                db('goods_specification_sku')->where('goods_id', 'in', $ids)->update(['deletetime' => $time]);
                $key_info = toArray($key_model->where('goods_id', 'in', $ids)->select());
                if ($key_info) {
                    $key_in_id = array();
                    foreach ($key_info as $k => $v) {
                        $key_in_id[$k] = $v['id'];
                    }
                }

                $collection = new CollectionGoods();
                $collection->whereIn('goods_id', $ids)->delete();
                db('goods_specification_key')->where('goods_id', 'in', $ids)->update(['deletetime' => $time]);
                db('goods_specification_val')->where('goods_specification_key_id', 'in', $key_in_id)->update(['deletetime' => $time]);
                $result = true;
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $result = $e->getMessage();
            }
            if ($result === true) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
